﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;

namespace ColorPicker
{
    class ColorHistogram
    {
        int bits = 6;
        public ColorHistogram(int colorBits)
        {
            bits = colorBits;
        }
        public ColorHistogram()
        {
        }
        Dictionary<Color, int> colors = new Dictionary<Color, int>();
        public Dictionary<Color, int> Colors { get { return colors; } }
        public unsafe void Create(Bitmap bm)
        {
            if (bm == null) return;
            colors.Clear();
            Dictionary<int, int> cd = new Dictionary<int, int>(10000);
            BitmapData bd = bm.LockBits(new Rectangle(0, 0, bm.Width, bm.Height),
                ImageLockMode.ReadOnly,
                PixelFormat.Format24bppRgb);
            byte* ptr = (byte*)bd.Scan0.ToPointer();
            int offset = bd.Stride - bm.Width * 3;
            int height = bm.Height;
            int width = bm.Width;
            int mask = (0xff00 >> bits) & 0xff;

            for (int i = 0; i < height; i++)
            {
                for (int j = 0; j < width; j++)
                {
                    int r = ptr[2]&mask;
                    int g = ptr[1]&mask;
                    int b = ptr[0]&mask;
                    int c = Color.FromArgb(r,g,b).ToArgb();
                    if (cd.ContainsKey(c)) ++cd[c];
                    else cd.Add(c, 1);
                    ptr += 3;
                }
                ptr += offset;
            }
            bm.UnlockBits(bd);
            foreach (KeyValuePair<int, int> p in cd)
                colors.Add(Color.FromArgb(p.Key), p.Value);
        }
    }
}
